package org.chen;

import redis.clients.jedis.Jedis;

public class StringJedisTest {
  public static void main(String[] args) {

    //连接redis,如果端口是6379可以只传host
    Jedis jedis = new Jedis("192.168.33.113",6379);

    //密码认证，这个要在配置文件中开启密码校验：requirepass 访问密码
//    jedis.auth("123456");

    //测试连接,如果返回pong,就证明连接成功
    System.out.println(jedis.ping());

    //清空redis数据库
    jedis.flushDB();

    //存值
    jedis.set("k1","hello");
    //取值
    System.out.println(jedis.get("k1"));

    //追加内容
    jedis.append("k1"," world!");
    System.out.println(jedis.get("k1"));

    //自增
    jedis.incr("k2");
    System.out.println(jedis.get("k2"));

    //按自定义整数步长自增
    jedis.incrBy("k2",10);
    System.out.println(jedis.get("k2"));

    //按自定义浮点数步长自增
    jedis.incrByFloat("k2",0.5);
    System.out.println(jedis.get("k2"));

    //自减
    jedis.decr("k3");
    System.out.println(jedis.get("k3"));

    //按自定义整数步长自减
    jedis.decrBy("k3",5);
    System.out.println(jedis.get("k3"));

    //批量存值
    jedis.mset("a1","apple","a2","aback","a3","4");
    //批量取值
    System.out.println(jedis.mget("a1", "a2", "a3"));

    //存值并添加有效期,单位为秒
    jedis.setex("k3",10,"v3");
    //查看key的有效期
    System.out.println(jedis.ttl("k3"));

    //存值并添加有效期,单位为毫秒
    jedis.psetex("k4",10000,"v4");
    System.out.println(jedis.ttl("k4"));

    //如果key不存在则存值(set if no exists)
    jedis.setnx("k5","redis");
    System.out.println(jedis.get("k5"));

    //批量存值，只要有一个存值不成功，则全部不会被存储
    jedis.msetnx("b1","baby","b2","baboon","a1","aaa");
    System.out.println(jedis.mget("b1", "b2", "a1"));

    //用value替换key的value从offset位开始的字符的值
    jedis.setrange("a2",3,"xx");
    System.out.println(jedis.get("a2"));

    //获取key的value的字符串长度
    System.out.println(jedis.strlen("a1"));

    //获取并更新一个key
    jedis.getSet("a2", "redis and jedis");
    System.out.println(jedis.get("a2"));

    //截取value，类似于substring
    System.out.println(jedis.getrange("a2", 0, 5));

    //获取key对应的string在offset处的bit值
    System.out.println(jedis.getbit("k2", 0));
    System.out.println(jedis.getbit("k2", 1));
    System.out.println(jedis.getbit("k2", 7));

    //设置或者清空key的value(字符串)在offset处的bit值
    System.out.println(jedis.get("k2"));
    jedis.setbit("k2",7,false);
    System.out.println(jedis.get("k2"));

    //统计字符串的bit值中为1的数量.
    System.out.println(jedis.bitcount("a3"));
  }
}
